import 'dart:math';

import 'package:permission_handler/permission_handler.dart';
import 'package:ycbl/plugin/gensee_live_plugin.dart';
import 'package:ycbl/utils/bl_permission_helper.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/utils/toast_util.dart';
import 'package:ycbl/ext/common_ext.dart';
import 'package:ycbl/utils/user_config.dart';

class LiveHelper {

  ///进入展示互动直播 or 回放
  static void startGensee(String liveUrl, String liveToken,
      String vodUrl, String vodToken, DateTime startTime, DateTime endTime) async{

    if (startTime == null || endTime == null) {
      LogUtil.e('参数错误 缺失直播时间');
      return;
    }

    bool hasPermission = await BLPermissionHelper.checkPermissions([Permission.storage, Permission.microphone, Permission.camera]);
    if (!hasPermission) {
      ToastUtil.showLongToast('请到设置中，给与直播需要的【存储】【相机】【麦克风】的权限');
      return;
    }

    var userName = UserConfig().getUserName() ?? UserConfig().getNickName() ?? '游客：${Random().nextInt(1000000)}';

    //已过回放时间，认为直播结束
    if (_isReplay(endTime)) {
      //没有回放
      if (vodUrl == null) {
        ToastUtil.showShortToast('暂无回放');
      }else {
        GenseeLivePlugin().startVod(vodUrl.getGenseeNumber(), vodToken ?? '222222', userName);
      }

    }else {
      //直播
      if (liveUrl == null) {
        ToastUtil.showShortToast('暂无直播');
      }else if (_canJoinLive(startTime)) {
        GenseeLivePlugin().startLive(liveUrl.getGenseeNumber(), liveToken ?? '333333', userName);
      }else {
        ToastUtil.showShortToast('直播尚未开始');
      }
    }

  }

  ///是否为回放
  static bool _isReplay(DateTime endTime) {
    //当前时间 > 直播结束时间 说明已结束
    return endTime.isBefore(DateTime.now());
  }

  /// 可提前 15 分钟进入直播
  static bool _canJoinLive(DateTime startTime) {
    var canJoinTime = startTime.subtract(Duration(minutes: 15));
    return DateTime.now().isAfter(canJoinTime);
  }

}